#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QMenuBar>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QPushButton>
#include <QTabWidget>
#include <QTextEdit>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QDockWidget>
#include <QTableWidget>
#include <QAction>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    resize(600,400);

    QMenuBar *bar = menuBar();
    setMenuBar(bar);

    bar->addMenu("文件");

    QMenu *viewMenu = bar->addMenu("视图");
    QMenu *installMenu = bar->addMenu("设置");
    QMenu *helpMenu = bar->addMenu("帮助");

    connect(viewMenu->addAction("新视图"), &QAction::triggered, this, &MainWindow::handleMyButtonClick);

    // --- 创建工具栏 ---
    QToolBar *toolBar = new QToolBar("主工具栏", this);
    addToolBar(Qt::TopToolBarArea, toolBar);
    toolBar->setToolButtonStyle(Qt::ToolButtonTextOnly); // 只显示文字

    // --- 创建标签页容器 ---
    QTabWidget *tabWidget;
    tabWidget = new QTabWidget(this);
    setCentralWidget(tabWidget);

    // --- 自定义内容数组 ---
    QStringList contents = {
        "这是选项1的窗口内容",
        "这是选项2的窗口内容",
        "这是选项3的窗口内容",
        "这是选项4的窗口内容",
        "这是选项5的窗口内容"
    };

    // --- 添加5个操作选项 ---
    for (int i = 0; i < 5; ++i) {
        QString buttonText = QString("选项%1").arg(i + 1);
        QAction *action = new QAction(buttonText, this);
        toolBar->addAction(action);

        connect(action, &QAction::triggered, this, [=]() {
            if (!windowsMap.contains(action)) {
                // 创建新窗口
                QWidget *win = new QWidget();
                win->setAttribute(Qt::WA_DeleteOnClose); // 关闭自动删除
                win->setWindowTitle(buttonText);

                QVBoxLayout *layout = new QVBoxLayout(win);
                QLabel *label = new QLabel(contents[i], win);
                label->setAlignment(Qt::AlignCenter);
                layout->addWidget(label);

                // 窗口关闭时从 map 移除指针
                connect(win, &QWidget::destroyed, this, [=]() {
                    windowsMap.remove(action);
                });

                win->resize(300, 200);
                win->show();

                windowsMap[action] = win;
            } else {
                // 窗口已存在，关闭它
                QWidget *win = windowsMap[action];
                if (win) {
                    win->close();  // 关闭时会触发destroyed，自动从map移除
                }
            }
        });
    }




    // 创建状态栏
    QStatusBar *statusBar = new QStatusBar(this);
    setStatusBar(statusBar);

    // 创建三个标签区域
    QLabel *leftLabel = new QLabel("左侧状", this);
    QLabel *rightLabel1 = new QLabel("右侧状态t", this);
    QLabel *rightLabel2 = new QLabel("右侧状态2：已连接", this);

    // 添加到状态栏
    statusBar->addWidget(leftLabel);               // 左对齐区域
    statusBar->addPermanentWidget(rightLabel1);    // 右对齐区域1
    statusBar->addPermanentWidget(rightLabel2);    // 右对齐区域2

    // 可动态修改内容：
    leftLabel->setText("状态1");
    rightLabel1->setText("状态2");
    rightLabel2->setText("状态3");


    statusBar->addWidget(leftLabel);
    statusBar->addPermanentWidget(rightLabel1);
    statusBar->addPermanentWidget(rightLabel2);

    // 创建中央部件，放表格和按钮
    QWidget *central = new QWidget(this);
    setCentralWidget(central);

    // 创建表格 8行5列
    tableWidget = new QTableWidget(8, 5, central);

    // 设置表头（自定义，示例用数字1~5）
    QStringList headers;
    for (int i = 1; i <= 5; ++i) {
        headers << QString::number(i);
    }
    tableWidget->setHorizontalHeaderLabels(headers);

    // 填充表格内容，示例用1~40
    int number = 1;
    for (int row = 0; row < 8; ++row) {
        for (int col = 0; col < 5; ++col) {
            tableWidget->setItem(row, col, new QTableWidgetItem(QString::number(number++)));
        }
    }

    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 创建切换顺序按钮
    toggleButton = new QPushButton("倒序显示", central);
    pushtxtButton = new QPushButton("传输信息",central);

    // 连接按钮点击信号
    connect(toggleButton, &QPushButton::clicked, this, &MainWindow::toggleTableOrder);

    connect(pushtxtButton, &QPushButton::clicked, this, &MainWindow::startFileWriting);

    // 横向布局放表格和按钮
    QHBoxLayout *hLayout = new QHBoxLayout();
    hLayout->addWidget(tableWidget);
    hLayout->addWidget(toggleButton);
    hLayout->addWidget(pushtxtButton);


    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(central);
    mainLayout->addLayout(hLayout);
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleMyButtonClick()
{
    QWidget *newView = new QWidget();
    newView->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动释放内存
    newView->resize(400, 300);
    newView->setWindowTitle(tr("新视图窗口 %1").arg(++pageCount));
    newView->show();
}

void MainWindow::toggleTableOrder()
{
    if (!tableWidget) return;

    int rows = tableWidget->rowCount();
    int cols = tableWidget->columnCount();

    // 交换行数据实现倒序
    for (int i = 0; i < rows / 2; ++i) {
        int opposite = rows - 1 - i;
        for (int j = 0; j < cols; ++j) {
            QTableWidgetItem *item1 = tableWidget->takeItem(i, j);
            QTableWidgetItem *item2 = tableWidget->takeItem(opposite, j);
            tableWidget->setItem(i, j, item2);
            tableWidget->setItem(opposite, j, item1);
        }
    }

    // 切换按钮文字
    isReversed = !isReversed;
    toggleButton->setText(isReversed ? "恢复顺序" : "倒序显示");
}


void MainWindow::startFileWriting()
{
    QString dir = QFileDialog::getExistingDirectory(this, "选择路径");
    if (dir.isEmpty())
        return;

    QString filePath = QDir(dir).filePath("hello.txt");

    QThread *thread = new QThread(this);
    FileWriterWorker *worker = new FileWriterWorker(filePath);
    worker->moveToThread(thread);

    connect(thread, &QThread::started, worker, &FileWriterWorker::writeFile);
    connect(worker, &FileWriterWorker::finished, this, [=]() {
        QMessageBox::information(this, "提示", "写入完成！");
        thread->quit();
    });
    connect(worker, &FileWriterWorker::error, this, [=](const QString &msg) {
        QMessageBox::warning(this, "错误", msg);
        thread->quit();
    });

    connect(thread, &QThread::finished, worker, &QObject::deleteLater);
    connect(thread, &QThread::finished, thread, &QObject::deleteLater);

    thread->start();
}
